package com.luochen.cdpt.service;

import com.luochen.cdpt.eneity.OrgInfo;
import com.luochen.cdpt.eneity.Page;
import com.luochen.cdpt.response.RespBean;
import com.luochen.cdpt.repository.IOrgInfoRepository;
import com.luochen.cdpt.util.BeanUtils;
import com.luochen.cdpt.util.SqlUtil;
import com.luochen.cdpt.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: star
 * @Date: 2018/12/16 09:42
 * @Description:
 */
@Service
public class OrgService {
    @Autowired
    IOrgInfoRepository orgInfoRepository;

    @Autowired
    EntityManager entityManager;

    public Page<OrgInfo> list(HttpServletRequest request) {
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("orgcde", request.getParameter("orgcde"));// 机构代码：orgcde
            paramMap.put("status", request.getParameter("status"));// 状态：status
            String sql = SqlUtil.bulidSql("OrgInfo", paramMap);
            String orgname = request.getParameter("orgname");
            if (!StringUtils.isEmptry(orgname)) {
                sql = sql + " and orgname like '%" +orgname+ "%'";
            }
            String tcrttm = request.getParameter("tcrttm");
            if (!StringUtils.isEmptry(tcrttm)) {
                sql = sql + " and date_format(tcrttm,'%Y-%m-%d') =:tcrttm";
            }
            sql = sql +" Order By tcrttm desc ";
            Query query = entityManager.createQuery(sql);
            if (!StringUtils.isEmptry(tcrttm)) {
                query.setParameter("tcrttm",tcrttm);
            }
            int totalCount = query.getResultList().size();
            SqlUtil.setPageParam(request, query);
            List<OrgInfo> list = query.getResultList();
            return Page.of(totalCount, list);
        } catch (Exception e) {
            e.printStackTrace();
            return Page.error("查询失败");
        }
    }

    /**
     * 保存、更新
     * @param orgInfo
     * @return
     */
    @Transactional
    public RespBean save(OrgInfo orgInfo) {
        try {
            OrgInfo org;
            if (null != orgInfo.getId()) {
                org = orgInfoRepository.findById(orgInfo.getId()).get();
                BeanUtils.copyPropertiesNotNull(org, orgInfo);
            } else {
                org = orgInfo;
            }
            orgInfoRepository.save(org);
            return RespBean.ok("保存成功", org);
        } catch (Exception e) {
            return RespBean.error("保存失败");
        }
    }
}
